﻿#region Header
//************************************************************************************
// Name: TemplateEngineManager
// Description: Class Used to generate the content of VM.template based on the entity passed
// Created On:  02-Aug-2011
// Created By:  Swathi
// Last Modified On:
// Last Modified By:
// Last Modified Reason:
//*************************************************************************************
#endregion Header
using System.Collections.Generic;
using System.IO;
using Commons.Collections;
using NVelocity;
using NVelocity.App;

    #region "Namespaces"

//using System.Web.HttpContext;

#endregion

namespace Base.Utils
{
    /// <summary>
    /// Used to generate the content of VM.template based on the entity passed
    /// </summary>
    /// <remarks></remarks>
    public sealed class TemplateEngineManager
    {
        /// <summary>
        /// This generic method is used to return a string by using content of VM file
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="vmFileName"></param>
        /// <param name="vmTemplateFolderPath"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string GetTemplate<T>(T entity, string vmFileName, string vmTemplateFolderPath)
        {
        
            var props = new ExtendedProperties();
            props.SetProperty("file.resource.loader.path", vmTemplateFolderPath);
            Velocity.Init(props);
            Template template = Velocity.GetTemplate(vmFileName, "gb2312");
            var context = new VelocityContext();
            //Check whether the entity is a Dictionary (array + object)
            if (entity.GetType().Name.StartsWith("Dictionary"))
            {
                var oDic = entity as Dictionary<string, object>;
                if (oDic != null)
                    foreach (string key in oDic.Keys)
                    {
                        context.Put(key, oDic[key]);
                    }
            }
            else
            {
                //If the entity consists of only object other than arrays    
                context.Put(entity.GetType().Name, entity);
            }
            var writer = new StringWriter();
            template.Merge(context, writer);
            return writer.GetStringBuilder().ToString();
        }
    }
}